package com.typhoon.dao;

import com.typhoon.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> findById(Long id) {
        return this.jdbcTemplate.query("select * from User where id = ? ",BeanPropertyRowMapper.newInstance(User.class),id);
    }

    public User save(User user) {
        List<Object> list = new ArrayList<>();
        list.add(user.getName());
        list.add(user.getSex());
        list.add(user.getAge());
        String sql = "insert into User values(null,?,now(),?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement pst = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    for (int i = 0; i < list.size(); i++) {
                        pst.setObject(i + 1, list.get(i));
                    }
                return pst;
            }
        }, keyHolder);
        return user;
    }

    public int deleteByPK(Long id) {
        return this.jdbcTemplate.update("delete from User where id = ?",id);
    }

}
